package com.lh_travel.lohas.base;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.gyf.barlibrary.ImmersionBar;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.activity.HomeActivity;
import com.lh_travel.lohas.dialogFragment.progressDialogFragment;
import com.lh_travel.lohas.interfaces.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public abstract class baseActivity extends AppCompatActivity {

    public Context mContext = baseActivity.this;
    public MainApplication mApp;
    private PermissionListener perListener;
    private progressDialogFragment loadingFragment;
    public ImmersionBar immersionBar;
    private boolean isResumed;
    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationOption = null;

    private String Tag = "baseActivity";

    public AlertDialog dialog;
    public AlertDialog dialog2;
    public View toastView;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mApp = (MainApplication) baseActivity.this.getApplication();
        initStatusBar();

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        mLocationOption.setOnceLocation(true);

        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
    }

    /**
     * amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
     amapLocation.getLatitude();//获取纬度
     amapLocation.getLongitude();//获取经度
     amapLocation.getAccuracy();//获取精度信息
     amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
     amapLocation.getCountry();//国家信息
     amapLocation.getProvince();//省信息
     amapLocation.getCity();//城市信息
     amapLocation.getDistrict();//城区信息
     amapLocation.getStreet();//街道信息
     amapLocation.getStreetNum();//街道门牌号信息
     amapLocation.getCityCode();//城市编码
     amapLocation.getAdCode();//地区编码
     amapLocation.getAoiName();//获取当前定位点的AOI信息
     amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
     amapLocation.getFloor();//获取当前室内定位的楼层
     amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
     //获取定位时间
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     Date date = new Date(amapLocation.getTime());
     df.format(date);
     * @param mLocationListener
     */
    public void autoLocation(AMapLocationListener mLocationListener) {

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

        if(null != mLocationClient){
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效


            mLocationClient.startLocation();
        }

    }

    public void showMyDialog(String title, String text, String confirm, String cancle, View.OnClickListener confirmListener){

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = View.inflate(mContext, R.layout.dialog_tos, null);

        builder.setView(view);

        if (title != null && title.length() > 0){
            TextView tv_title = view.findViewById(R.id.tv_title);
            tv_title.setText(title);
        }

        if (text != null && text.length() > 0){
            TextView tv_content = view.findViewById(R.id.tv_content);
            tv_content.setText(text);
        }

        RelativeLayout rl_button = view.findViewById(R.id.rl_button);
        Button btn_cancle = view.findViewById(R.id.btn_cancle);
        Button btn_confirm = view.findViewById(R.id.btn_confirm);

        if (confirm !=null && confirm.length() > 0){
            btn_confirm.setText(confirm);

            btn_confirm.setOnClickListener(confirmListener);

        }else {
            btn_confirm.setVisibility(View.GONE);
        }

        if (cancle !=null && cancle.length() > 0){
            btn_cancle.setText(cancle);

            btn_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

        }else {
            btn_cancle.setVisibility(View.GONE);
        }

        if ((confirm == null || confirm.length() == 0) && (cancle == null || cancle.length() == 0)){
            rl_button.setVisibility(View.GONE);
        }
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();

    }

    public void showMyDialog2(String title, String text, String confirm, String cancle, View.OnClickListener confirmListener, View.OnClickListener cancleListener){

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = View.inflate(mContext, R.layout.dialog_tos, null);

        builder.setView(view);

        if (title != null && title.length() > 0){
            TextView tv_title = view.findViewById(R.id.tv_title);
            tv_title.setText(title);
        }

        if (text != null && text.length() > 0){
            TextView tv_content = view.findViewById(R.id.tv_content);
            tv_content.setText(text);
        }

        RelativeLayout rl_button = view.findViewById(R.id.rl_button);
        Button btn_cancle = view.findViewById(R.id.btn_cancle);
        Button btn_confirm = view.findViewById(R.id.btn_confirm);

        if (confirm !=null && confirm.length() > 0){
            btn_confirm.setText(confirm);

            btn_confirm.setOnClickListener(confirmListener);

        }else {
            btn_confirm.setVisibility(View.GONE);
        }

        if (cancle !=null && cancle.length() > 0){
            btn_cancle.setText(cancle);

            btn_cancle.setOnClickListener(cancleListener);
        }else {
            btn_cancle.setVisibility(View.GONE);
        }

        if ((confirm == null || confirm.length() == 0) && (cancle == null || cancle.length() == 0)){
            rl_button.setVisibility(View.GONE);
        }
        builder.setCancelable(false);

        dialog2 = builder.create();
        dialog2.show();

    }


    /**
     * 到应用详情界面
     * @return
     */
    public Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }

    public void showMessage(String msg) {
        Toast toast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
        toast.show();
        duration = 2000;
        toastView = toast.getView();

        toastView.postDelayed(new toastRunnable(new doInRunable() {
            @Override
            public void doIn() {

                toastView = null;
            }
        }), duration);

    }

    public abstract void findView();

    public abstract void bindListner();

    public abstract void ensureUI();

    public LinearLayout getContent() {
        return (LinearLayout) findViewById(R.id.ll_content);
    }

    /**
     * 初始化状态栏和导航栏,我设置成全屏透明状态栏导航栏,在导航栏的地方设置了一个透明的view,然后根据导航栏的高度,设置view'的高度.
     */
    private void initStatusBar() {

        immersionBar = ImmersionBar.with(this);
        immersionBar
               // .transparentNavigationBar()
                .transparentStatusBar()
                .fullScreen(false)
                .init();
       /* immersionBar.transparentStatusBar()  //透明状态栏，不写默认透明色
                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                .statusBarColor(R.color.colorPrimary)     //状态栏颜色，不写默认透明色
                .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                .statusBarAlpha(0.3f)  //状态栏透明度，不写默认0.0f
                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.btn3)  //修改flyme OS状态栏字体颜色
                .fullScreen(true)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                .addViewSupportTransformColor(toolbar)  //设置支持view变色，可以添加多个view，不指定颜色，默认和状态栏同色，还有两个重载方法
                .titleBar(view)    //解决状态栏和布局重叠问题，任选其一
                .titleBarMarginTop(view)     //解决状态栏和布局重叠问题，任选其一
                .statusBarView(view)  //解决状态栏和布局重叠问题，任选其一
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .supportActionBar(true) //支持ActionBar使用
                .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
                .removeSupportView(toolbar)  //移除指定view支持
                .removeSupportAllView() //移除全部view支持
                .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                .addTag("tag")  //给以上设置的参数打标记
                .getTag("tag")  //根据tag获得沉浸式参数
                .reset()  //重置所以沉浸式参数
                .keyboardEnable(true)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)  //单独指定软键盘模式
                .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                    }
                })
                .init();  //必须调用方可沉浸式
        */
    }

    /**
     * 显示跳转的动画
     */
    public void showViewLoad() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        Fragment prev = getSupportFragmentManager().findFragmentByTag("loadview");

        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        // Create and show the dialog.

        loadingFragment = new progressDialogFragment(mContext);

        loadingFragment.show(ft, "loadview");
    }

    /**
     * 取消第三方动画
     */
    public void dismissViewLoad() {
        if (loadingFragment != null) {

            loadingFragment.dismiss(isResumed);
        }

    }

    /**
     * 是否是华为
     */
    public static boolean isHUAWEI() {
        return android.os.Build.MANUFACTURER.equals("HUAWEI");
    }

    /**
     * 假如申请的是单个权限,就可以在perListener.onGranted中处理,否则需要在onDenied中处理;
     *
     * @param permissionList
     * @param perListener
     */
    public void checkMyPermission(List<String> permissionList, PermissionListener perListener) {

        this.perListener = perListener;

        ArrayList<String> requestPermissionsList = new ArrayList<>();

        for (int i = 0; i < permissionList.size(); i++) {

            if (ContextCompat.checkSelfPermission(mContext, permissionList.get(i))
                    != PackageManager.PERMISSION_GRANTED) {
                //记录要申请权限的index

                requestPermissionsList.add(permissionList.get(i));
            }

        }

        if (requestPermissionsList.size() != 0) {

            String[] str = new String[requestPermissionsList.size()];

            String[] permissions = requestPermissionsList.toArray(str);

            ActivityCompat.requestPermissions(baseActivity.this, permissions, 2);

        }else{
            perListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case 2:

                ArrayList<Integer> deneyList = new ArrayList<>();

                if (grantResults.length > 0) {

                    for (int i = 0; i < grantResults.length; i++) {

                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {

                            deneyList.add(i);
                        }
                    }

                    if (deneyList.size() == 0) {

                        //全部都没被拒绝
                        perListener.onGranted();

                    } else {
                        perListener.onDenied(deneyList);
                    }

                } else {

                    for (int i = 0; i < grantResults.length; i++) {
                        deneyList.add(i);
                    }

                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (immersionBar != null)
            immersionBar.destroy();  //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态

        if (mLocationClient != null){
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }

    public static class toastRunnable implements Runnable{

        private doInRunable doin;

        public toastRunnable( doInRunable doin) {
            this.doin = doin;
        }

        @Override
        public void run() {

            doin.doIn();

        }
    }

    public interface doInRunable{
        void doIn();
    }
}
